﻿using DzInfo.Model.KD;
using DzInfo.Tools;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.K3.FIN.App.Core.Match.Object;
using Newtonsoft.Json;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.SerivesPlugin.ChuangYuan
{
    [Description("创远：服务、维修确认单审核时自动生成费用应收单"), HotUpdate]
    public class CyCreatePayble : AbstractOperationServicePlugIn
    {
        /// <summary>
        /// 加载所有列
        /// </summary>
        /// <param name="e"></param>
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, this.BusinessInfo.GetForm().Id);
            var fieldKeyList = meta.BusinessInfo.GetBosFields().Select(x => x.Field.Key).ToList();
            for (int i = 0; i < fieldKeyList.Count; i++)
            {
                e.FieldKeys.Add(fieldKeyList[i]);
            }
        }
        public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        {
            base.BeforeExecuteOperationTransaction(e);
            foreach (var obj in e.SelectedRows.Select(s => s.DataEntity))
            {
                if (obj == null) { return; }
                if (e.Cancel == false)
                {
                    string formId = this.BusinessInfo.GetForm().Id;
                    string payableJson = GetPayable(obj, formId);
                    //调用接口，创建费用应收单
                    var apiResult = KDApi.Save(this.Context, "AR_receivable", payableJson);
                    if (!apiResult.Result.ResponseStatus.IsSuccess)
                    {
                        e.Cancel = true;
                        throw new Exception($"生成应收单失败：{payableJson}");
                    }
                }
            }
        }

        private string GetPayable(DynamicObject obj, string formId)
        {
            string ruleId = "";
            string tableName = "";
            string billnoType = "";
            if (formId == "keaeeb1b6ff5345c28ba84b2a7e3d095f")
            {
                ruleId = "55972b2b-a2d7-4000-9fe1-93dde6a8b9ae";
                tableName = "ora_t_Cust_Entry100010";
                billnoType = "WXYSD";
            }
            else
            {
                ruleId = "8f1ab7bb-9279-4f96-9a97-4c8dc5a7dde1";
                tableName = "POSW_t_fwqrdmx";
                billnoType = "FWYSD";
            }
            string fid = obj["id"].ToString();
            string custNumber = (obj["F_POSW_jskh"] as DynamicObject) == null ? "" : (obj["F_POSW_jskh"] as DynamicObject)["number"].ToString();
            string curNumber = (obj["F_POSW_jsbb"] as DynamicObject) == null ? "" : (obj["F_POSW_jsbb"] as DynamicObject)["number"].ToString();
            string orgNumber = (obj["F_POSW_jszz"] as DynamicObject) == null ? "" : (obj["F_POSW_jszz"] as DynamicObject)["number"].ToString();
            string hllx = (obj["F_POSW_hllx"] as DynamicObject) == null ? "" : (obj["F_POSW_hllx"] as DynamicObject)["number"].ToString();
            decimal hl = Convert.ToDecimal(obj["F_POSW_hl"]);
            int ysfx = Convert.ToInt32(obj["F_POSW_YSFX"]);
            DynamicObjectCollection rows = obj["FEntity"] as DynamicObjectCollection;
            decimal allamoun = rows.Select(s => Convert.ToDecimal(s["F_ora_Amount1"])).Sum(m => m);
            string date = DateTime.Now.ToString("yyyy-MM-dd");
            AR_receivable ar = new AR_receivable();
            ar.IsAutoSubmitAndAudit = "true";
            ar.Model = new Model.KD.Model()
            {
                FBillTypeID = new FBillTypeID() { FNUMBER = billnoType },
                FDATE = date,
                FENDDATE_H = date,
                FISINIT = "false",
                FCUSTOMERID = new FCUSTOMERID() { FNumber = custNumber },
                FCURRENCYID = new FCURRENCYID() { FNumber = curNumber },
                FISPRICEEXCLUDETAX = "true",
                FACCOUNTSYSTEM = new FACCOUNTSYSTEM() { FNumber = "" },
                FSETTLEORGID = new FSETTLEORGID() { FNumber = orgNumber },
                FSALEORGID = new FSALEORGID() { FNumber = orgNumber },
                FPAYORGID = new FPAYORGID() { FNumber = orgNumber },
                FISTAX = "true",
                FCancelStatus = "A",
                FBUSINESSTYPE = "",
                FMatchMethodID = 0,
                FAR_Remark = "审核自动生成",
                FSetAccountType = "",
                FISHookMatch = "false",
                FISINVOICEARLIER = "false",
                FWBOPENQTY = "false",
                FISGENERATEPLANBYCOSTITEM = "false",
                FAllAmountIsByTaxPrice = "false",
                FALLAMOUNTFOR = allamoun,
                FsubHeadFinc = new FsubHeadFinc()
                {
                    FACCNTTIMEJUDGETIME = date,
                    FMAINBOOKSTDCURRID = new FMAINBOOKSTDCURRID() { FNumber = curNumber },
                    FEXCHANGETYPE = new FEXCHANGETYPE() { FNumber = hllx },
                    FExchangeRate = hl
                }
            };
            ar.Model.FEntityDetail = new List<FEntityDetailItem>();
            foreach (var row in rows)
            {
                string eid = row["id"].ToString();
                decimal qty = 1m;
                if (ysfx == 2)
                {
                    qty = -qty;
                }
                decimal price = Convert.ToDecimal(row["F_ora_Amount1"]);
                decimal sl = Convert.ToDecimal(row["F_POSW_sl"]);
                FEntityDetailItem arRow = new FEntityDetailItem()
                {
                    FPriceQty = qty,
                    FBASICUNITQTY = qty,
                    FTaxPrice = price,
                    FPrice = price / (1 + sl / 100),
                    FEntryTaxRate = sl,
                    FNoTaxAmountFor_D = price / (1 + sl / 100) * qty,
                    FTAXAMOUNTFOR_D = (price / (1 + sl / 100) * qty) * sl / 100,
                    FALLAMOUNTFOR_D = price / (1 + sl / 100) * qty + (price / (1 + sl / 100) * qty) * sl / 100,
                    FEntityDetail_Link = new List<FEntityDetail_LinkItem>()
                    {
                        new FEntityDetail_LinkItem()
                        {
                            FEntityDetail_Link_FRuleId=ruleId,
                            FEntityDetail_Link_FSTableName=tableName,
                            FEntityDetail_Link_FSBillId=fid,
                            FEntityDetail_Link_FSId=eid
                        }
                    }
                };
                ar.Model.FEntityDetail.Add(arRow);
            }
            return JsonConvert.SerializeObject(ar, Formatting.Indented);
        }
    }
}
